import pymysql


def connect(db):  # 连接数据库的方法connect
    # db = {"host":"192.168.2.36","port":3306,"user":"root","pwd":"123456","dbname":"apple"}
    # db 是数据库的意思，
    user = db['user']
    host = db['host']
    port = db['port']
    pwd = db['pwd']
    dbname = db['dbname']

    try:
        conn = pymysql.connect(user=user,
                               password=pwd,
                               host=host,
                               database=dbname,
                               port=port,
                               charset='utf8')
        print("数据库连接成功")
        return conn
    except Exception as e:
        print(f"连接数据库失败，异常信息：{e}")


def disconnect(conn):
    try:
        conn.close()
        print(f"断开数据库连接")
    except  Exception as e:
        print(f"断开数据库连接失败，异常信息：{e}")

#执行sql方法
def execute(conn, sql):
    # 执行sql语句
    try:
        cursor = conn.cursor()  # 获取游标
        cursor.execute(sql)  # 用游标执行sql语句
        conn.commit()  # 提交
        cursor.close()  # 关闭游标
        print(f"执行sql语句{sql}成功")
    except  Exception as e:
        print(f"执行sql语句{sql}异常，异常信息：{e}")


def delete_user(db, phone):
    '''
    根据手机号码删除用户
    :param phone:
    :return:
    '''
    conn = connect(db)
    execute(conn, f"delete from member where mobilephone={phone}")
    disconnect(conn)


if __name__ == '__main__':
    db = {"host": "192.168.2.36", "port": 3306, "user": "root", "pwd": "123456", "dbname": "apple"}
    conn = connect(db)
    execute(conn, "delete from member where mobilephone=18012345678")
    disconnect(conn)
